/**
 * Created by shidaiapp on 2017/9/29.
 */


export const init = (self, tiyData) => {
  tiyData.tStatus.modalEmail.isShow = false;
  tiyData.tStatus.modalopRecord.isShow = false;
  tiyData.tParams.customerInfo.state = 0;
  tiyData.tParams.customerInfo.contactUrl = "";
  tiyData.tParams.customerInfo.externalEmail = "";
  tiyData.tParams.customerInfo.customerDesc = "";
  tiyData.tParams.customerInfo.isSendLetter = false;
  tiyData.tParams.opRecordSave.customerOperation = 0;
  tiyData.tParams.opRecordSave.operationDesc = "";
  tiyData.tParams.opRecordSave.operationTime = "";
  tiyData.tParams.changeStateCustomerInfo.number = "";
  tiyData.tParams.changeStateCustomerInfo.id = "";
  tiyData.tParams.searchInfo.state = 120;
  tiyData.tParams.searchInfo.customerName = "";
  tiyData.tParams.searchInfo.number = "";
  tiyData.tParams.searchInfo.isHasShop = false;
  tiyData.tParams.searchInfo.startTime = "";
  tiyData.tParams.searchInfo.endTime = "";
  tiyData.tParams.searchInfo.orderBy = "";
  tiyData.tParams.searchInfo.tags = "";
  tiyData.tPage.stepNumber = 20;
  tiyData.tPage.currentPage = 1;
  tiyData.tPage.total = 1;
};

/**
 * 从服务器请求列表
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const searchService = (self, tiyData) => {
  self.$Spin.show();
  let data = {
    "pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "state": tiyData.tParams.searchInfo.state,
    "customerName": tiyData.tParams.searchInfo.customerName,
    "number": tiyData.tParams.searchInfo.number,
    "isHasShop": tiyData.tParams.searchInfo.isHasShop,
    "orderBy": tiyData.tParams.searchInfo.orderBy,
    "tags": tiyData.tParams.searchInfo.tags,
    "otherTags":tiyData.tParams.searchInfo.otherTags,
  };
  if (tiyData.tParams.searchInfo.startTime) {
    data.startTime = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.searchInfo.startTime).getTime())
  } else {
    data.startTime = "";
  }
  if (tiyData.tParams.searchInfo.endTime) {
    data.endTime = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.searchInfo.endTime).getTime())
  } else {
    data.endTime = "";
  }
  self.$apiPlugin.targetCustomerManegeList(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let userPage = response.result;
      tiyData.tData.userList.splice(0, tiyData.tData.userList.length);;
      tiyData.tPage.total = userPage.total;
      tiyData.tPage.stepNumber = userPage.pageSize;
      userPage.list.forEach(
        function (item) {
          tiyData.tData.userList.push(item);
          if (item.state == 300 || item.state == 310){
            item._disabled = true;
          }
        }
      );
      self.selectedIds.splice(0);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 设置用户状态
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const saveBatchCustomers = (self, tiyData) => {
  self.$Spin.show();
  // tiyData.tParams.batchCustomer.customerIds.length = 0;
  // tiyData.tParams.selectedCustomers.forEach(function (item) {
  //   tiyData.tParams.batchCustomer.customerIds.push(item.id);
  // });
  tiyData.tParams.batchCustomer.customerIds.splice(0, tiyData.tParams.batchCustomer.customerIds.length, ...self.selectedIds);
  self.$apiPlugin.batchSetCustomerState({
    customerIds: tiyData.tParams.batchCustomer.customerIds,
    state: tiyData.tParams.batchCustomer.state,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.config("批量保存状态成功");
      tiyData.tParams.selectedCustomers.splice(0, tiyData.tParams.selectedCustomers.length);
      searchService(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 查询操作记录
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const queryCustomerOpRecord = (self, tiyData) => {
  self.$Spin.show();
  self.$apiPlugin.queryCustomerOpRecord({
    customerId: tiyData.tParams.opRecordQuery.customerId,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.opRecordList.length = 0;
      response.result.forEach(function (item) {
        let operation = self.customerOperation.filter(opItem => opItem.value == item.operation);
        item.operationStr = null != operation && operation.length > 0 ? operation[0].name : " ";
        item.createTime = self.$tiyBJTime(item.createtime);
        tiyData.tData.opRecordList.push(item);
      });
      tiyData.tParams.opRecordSave.customerOperation = 0,
        tiyData.tParams.opRecordSave.operationDesc = "",
        tiyData.tParams.opRecordSave.operationTime = self.$tiyBJTime(new Date().getTime());
        tiyData.tStatus.modalopRecord.isShow = true;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 保存操作记录
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const saveCustomerOpRecord = (self, tiyData) => {
  self.$Spin.show();
  self.$apiPlugin.saveCustomerOpRecord({
    customerId: tiyData.tParams.opRecordSave.customerId,
    customerOperation: tiyData.tParams.opRecordSave.customerOperation,
    operationDesc: tiyData.tParams.opRecordSave.operationDesc,
    operationTime: tiyData.tParams.opRecordSave.operationTime != null
    && tiyData.tParams.opRecordSave.operationTime > 0 ?
      tiyData.tParams.opRecordSave.operationTime.getTime() : null,
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      queryCustomerOpRecord(self, tiyData);
      self.$Message.config("保存操作成功")
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 设置用户状态 用户扩展邮箱
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const saveCustomer = (self, tiyData, isEmail) => {
  let customerInfo = tiyData.tParams.customerInfo;
  if (isEmail) {
    if (customerInfo.contactUrl == ""
      && customerInfo.externalEmail == ""
      && customerInfo.customerDesc == ""
      &&customerInfo.externalUrl==""
      && !customerInfo.isSendLetter) {
      changeModelColorLoading(self, tiyData);
      return;
    }
  }
  if(customerInfo.tags.length==0){
    self.$Message.error('请添加网站分类标签');
    changeModelColorLoading(self, tiyData);
    return;
  };
  self.$refs["paramCustomer"].validate((valid) => {
    if (valid) {
      self.$Spin.show();
      if (customerInfo.isSendLetter) {
        customerInfo.state = 500;
      };
      var tags=[];
      customerInfo.tags.forEach(function(item,index){
        tags.push({
          customerId:customerInfo.id,
          type:2,
          tag:item,
          sequence:index
        })
      });
      customerInfo.otherTags.forEach(function(item,index){
        tags.push({
          customerId:customerInfo.id,
          type:9,
          tag:item,
          sequence:index
        })
      });
      let data = {
        customerId: customerInfo.id,
        contactUrl: customerInfo.contactUrl,
        externalUrl:customerInfo.externalUrl, //个人主页
        externalEmail: customerInfo.externalEmail,
        customerDesc: customerInfo.customerDesc,
        state: customerInfo.state,
        extendInfo:customerInfo.extendInfo,
        tags:tags,
        customerName:customerInfo.customerName,
        contacts:customerInfo.contacts

      };
      self.$apiPlugin.saveCustomerInfo(data).then(function (response) {
        self.$Spin.hide();
        if (response.success) {
          changeModelColorLoading(self, tiyData);
          self.$Message.config("保存扩展信息成功");
          searchService(self, tiyData);
          tiyData.tStatus.modalEmail.isShow = false;
          tiyData.tStatus.modalEmail.hasName = false;
          customerInfo.name = "";
          customerInfo.state = 0;
          customerInfo.contactUrl ="";
          customerInfo.externalEmail = "";
          customerInfo.externalUrl = "";
          customerInfo.customerDesc = "";
          customerInfo.isSendLetter = false;
        } else {
          changeModelColorLoading(self, tiyData);
          self.$Message.error(response.errorMessage);
        }
      });
    } else {
      changeModelColorLoading(self, tiyData);
    }
  });
};

/**
 * 更改用户状态
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const changeCustomerState = (self, tiyData, state) => {
  self.$Spin.show();
  let api; //后台api
  let ret = false;
  let data = {
    "customerId": tiyData.tParams.changeStateCustomerInfo.id,
    "number" : tiyData.tParams.changeStateCustomerInfo.number
  };
  switch(state){
    case 200:
      api = self.$apiPlugin.setCustomerEffective;
      break;
    case 300:
      api = self.$apiPlugin.customerInfoSetInvalid;
      break;
    default:
      ret = true;
      break;
  }
  if(ret){
    self.$Message.error("错误的状态！");
    return;
  }
  api(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      searchService(self, tiyData);
      self.$Message.config("保存状态成功")
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 用户详情信息
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const getCustomerInfo = (self, tiyData,id, state) => {
  self.$Spin.show();
  self.$ySpliceAll(tiyData.tParams.customerInfo.tags, tiyData.tParams.customerInfo.readonlyTags,
    tiyData.tParams.customerInfo.otherTags, tiyData.tParams.customerInfo.contacts,tiyData.tParams.customerInfo.opRecords);
  self.$apiPlugin.getCustomerInfoById({ "customerId": id,"state":state}).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      let result = response.result;

      tiyData.tParams.customerInfo.id = result.id;
      tiyData.tParams.customerInfo.customerName = result.name;
      switch(result.channel){
        case 1:
          tiyData.tParams.customerInfo.channel = "Instagram";
          break;
        case 2:
          tiyData.tParams.customerInfo.channel = "Shopify";
          break;
        case 3:
          tiyData.tData.customerInfo.channel = "BigCommerce";
          break;
        case 5:
          tiyData.tData.customerInfo.channel = "线下采集";
          break;
        default:
          tiyData.tParams.customerInfo.channel = "";
          break;
      }

      tiyData.tParams.customerInfo.avatar = result.avatar;
      tiyData.tParams.customerInfo.externalUrl = result.externalUrl;
      tiyData.tParams.customerInfo.fullName = result.fullName;
      tiyData.tParams.customerInfo.email = result.email;
      tiyData.tParams.customerInfo.externalEmail = result.externalEmail;
      tiyData.tParams.customerInfo.state = result.state;
      tiyData.tParams.customerInfo.stateTitle = self.targetCustomerStateDict.filter(item => item.value == result.state)[0].name;
      tiyData.tParams.customerInfo.number = result.number;
      // tiyData.tParams.customerInfo.description = result.description;
      tiyData.tParams.customerInfo.employeeId = result.employeeId;
      tiyData.tParams.customerInfo.employeeName = result.employeeName;
      tiyData.tParams.customerInfo.createtime = self.$tiyBJTime(result.createtime);
      tiyData.tParams.customerInfo.country = result.country;
      tiyData.tParams.customerInfo.contactUrl = result.contactUrl;

      if(result.customerTagList.length>0){
        result.customerTagList.forEach(function(item,index){
          switch(item.type) {
            case 1:
              tiyData.tParams.customerInfo.readonlyTags.push(item.tag);
              break;
            case 2:
              tiyData.tParams.customerInfo.tags.push(item.tag);
              break;
            case 9:
              tiyData.tParams.customerInfo.otherTags.push(item.tag);
              break;
          }
        })
      }
      if(result.customerExtendInfo){
        tiyData.tParams.customerInfo.extendInfo = Object.assign({},result.customerExtendInfo);
        tiyData.tParams.customerInfo.extendInfo.facebook=formatContactUrl(tiyData.tParams.customerInfo.extendInfo.facebook);
        tiyData.tParams.customerInfo.extendInfo.twitter=formatContactUrl(tiyData.tParams.customerInfo.extendInfo.twitter);
        tiyData.tParams.customerInfo.extendInfo.instagram=formatContactUrl(tiyData.tParams.customerInfo.extendInfo.instagram);
        tiyData.tParams.customerInfo.extendInfo.pinterest=formatContactUrl(tiyData.tParams.customerInfo.extendInfo.pinterest);
      }

      if(result.customerContacts &&result.customerContacts.length>0){
       result.customerContacts.forEach(function(item,index){
         tiyData.tParams.customerInfo.contacts.push(item)
       })
      }

      result.opRecords.forEach(function (item) {
        let record = item;
        record.employeeName = tiyData.tParams.customerInfo.employeeName;
        tiyData.tParams.customerInfo.opRecords.push(record);
      });

    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

function changeModelColorLoading(self, tiyData) {
  tiyData.tStatus.modalEmail.isLoading = false;
  self.$nextTick(function () {
    tiyData.tStatus.modalEmail.isLoading = true;
  });
}

/**
 * 分配负责员工
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const assignEmployee = (self, tiyData) => {
  self.$Spin.show();
  let userIds = [];
  tiyData.tParams.selectedCustomers.forEach(user =>{
    userIds.push(user.id);
  });
  let data = {
    "employeeId":tiyData.tParams.selectedEmployee.id,
    "employeeName":tiyData.tParams.selectedEmployee.userName,
    "userIds":userIds
  }
  self.$apiPlugin.assignToEmployee(data).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success("分配负责员工成功。");
      tiyData.tParams.selectedCustomers.splice(0, tiyData.tParams.selectedCustomers.length);
      searchService(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 查询员工
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const getEmployees = (self, tiyData) => {
  // self.$Spin.show();
  tiyData.tParams.selectedEmployee = {}; //清空之前选择的员工
  self.$apiRole.getPromoteEmployee({}).then(function (response) {
    if (response.success) {
      let employeeList = response.result;
      tiyData.tData.employeeList.splice(0, tiyData.tData.employeeList.length);
      employeeList.forEach(
        function (item) {
          tiyData.tData.employeeList.push(item);
        });
    } else {
      self.$Message.error(response.errorMessage);
    }
    // self.$Spin.hide();
  });
};

function formatContactUrl(url){
  if(url!=''&&url!=null && url.indexOf('?')!=-1){
    return url.substring(0,url.indexOf('?'));
  }
  return url;
}
